import MySQLdb

from django.contrib.auth.models import User
from django.core.validators import email_re
from django.conf import settings

import sys
import crypt

def dbquery(in_user):
    dbopts = settings.DATABASES['ISPConfig']
    database=MySQLdb.connect(dbopts.get('HOST',''),dbopts.get('USER','ispconfig'), \
                                dbopts.get('PASSWORD',''), dbopts.get('NAME','dbispconfig'))
    dbcur=database.cursor()
    dbcur.execute("SELECT email,password FROM mail_user WHERE email ='%s'" % in_user )
    return dbcur.fetchone()

class ISPConfigAuth(object):
    supports_anonymous_user = False
    supports_object_permissions = False

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

    def authenticate(self, username=None, password=None):
        response = None
        dbres = dbquery(username)
        try:
            user = User.objects.get(username=username)
            if crypt.crypt(password, dbres[1]) == dbres[1]:
                response = user

        except User.DoesNotExist:
            if crypt.crypt(password, dbres[1])==dbres[1]:
                user = User(username=username,email=dbres[0],password=_("handled by ispconfig"))
                user.save()
                response = user

        return response
